<?php

namespace Keio\StudyBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Response;

use Keio\StudyBundle\Entity\Baihoc;
use Keio\StudyBundle\Entity\Baihoccauhoi;
use Keio\StudyBundle\Form\BaihocType;

/**
 * Baihoc controller.
 *
 */
class BaihocController extends Controller
{

	//show va add câu hỏi vào bài học
	public function showAction($id){
		//lấy các câu hỏi đã gắn vào bài học
		$em = $this->getDoctrine()->getManager();
        $cauhoiY = $em->getRepository('KeioStudyBundle:Cauhoi')->getCauhoiByBaihocId($id);

		//những câu chưa gắn được lấy theo môn học, dùng ajax (xem controller sau)
		$monhoc = $em->getRepository('KeioStudyBundle:Monhoc')->findAll();
		//đẩy lên view
		return $this->render('KeioStudyBundle:Baihoc:addcauhoi.html.twig', array(
            'cauhoiY' => $cauhoiY,
            'monhoc'  => $monhoc,
            'baihocid'=> $id,
        ));
	}
	//action cho Ajax add câu hỏi vào bài học
	public function getcauhoichuaganbymonhocAction($baihoc_id, $monhoc_id){
		$em = $this->getDoctrine()->getManager();
        //Lấy các câu hỏi đã gắn vào bài (để exclude sau đó)
		$cauhoiY = $em->getRepository('KeioStudyBundle:Cauhoi')->getCauhoiByBaihocId($baihoc_id);
		$array_id = array();
		for ($j=0; $j<count($cauhoiY); $j++){
			$array_id[] = $cauhoiY[$j]['id'];
		}
		//lấy các câu hỏi của môn học exclude array_id
		$toto = $em->getRepository('KeioStudyBundle:Cauhoi')->getCauhoiByMonhocExcludeSomeId($monhoc_id, $array_id);
		//xây dựng checkbox
		$out = '';
		for ($j=0; $j<count($toto);$j++){
			if ($toto[$j]['loai']==0){
				$inf = ' (câu hỏi trắc nghiệm)';
			}else{
				$inf = ' (câu hỏi điền trả lời)';
			}
			$out = $out.'<br>'.'<input '.'id="checkbox'.$j.
					'" type="checkbox" name="cauhoi[]" value="'.$toto[$j]['id'].
					'" onChange="checkform()"> '.$toto[$j]['tieude'].$inf;
		}
		return new Response($out);
	}

	//add cauhoi to baihoc
	//cau hoi ID lay tu form submit
	public function addcauhoitobaihocAction($baihoc_id){
		$request = $this->getRequest();
		$array_cauhoi = $request->request->get('cauhoi');

		$em = $this->getDoctrine()->getManager();
		$baihoc = $em->getRepository('KeioStudyBundle:Baihoc')->find($baihoc_id);

		for ($j=0; $j<count($array_cauhoi); $j++){
			$cauhoi = $em->getRepository('KeioStudyBundle:Cauhoi')->find($array_cauhoi[$j]);
			$tmp = new Baihoccauhoi();
			$tmp->setBaihoc($baihoc);
			$tmp->setCauhoi($cauhoi);
			$em->persist($tmp);
        	$em->flush();
		}
		return $this->redirect($this->generateUrl('keio_baihoc_show', array('id'=>$baihoc_id)));
	}

    /**
     * Lists all Baihoc entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('KeioStudyBundle:Baihoc')->findAll();

        //set delete form cho mỗi element
        foreach ($entities as $bh){
        	$deleteForm = $this->createDeleteForm($bh->getId());
        	$bh->setDelform($deleteForm->createView());
        }

        $entity = new Baihoc();
        $form   = $this->createForm(new BaihocType(), $entity);

        return $this->render('KeioStudyBundle:Baihoc:index.html.twig', array(
            'entities' => $entities,
            'form'   => $form->createView(),
        ));
    }
    /**
     * Creates a new Baihoc entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Baihoc();
        $form = $this->createForm(new BaihocType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('keio_baihoc'));
        }
    }

    /**
     * Displays a form to create a new Baihoc entity.
     *
     */
    public function newAction()
    {
        $entity = new Baihoc();
        $form   = $this->createForm(new BaihocType(), $entity);

        return $this->render('KeioStudyBundle:Baihoc:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Baihoc entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:Baihoc')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Baihoc entity.');
        }

        $editForm = $this->createForm(new BaihocType(), $entity);

        return $this->render('KeioStudyBundle:Baihoc:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }

    /**
     * Edits an existing Baihoc entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('KeioStudyBundle:Baihoc')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Baihoc entity.');
        }

        $editForm = $this->createForm(new BaihocType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('keio_baihoc'));
        }

        return $this->render('KeioStudyBundle:Baihoc:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        ));
    }
    /**
     * Deletes a Baihoc entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('KeioStudyBundle:Baihoc')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Baihoc entity.');
            }

            //check if contraint
			$checkconstraint = $em->getRepository('KeioStudyBundle:Baihoc')->checkConstraintToDeleteBaihoc($id);
			if ($checkconstraint==1){ //having constraint
				$this->get('session')->getFlashBag()->add('msg', 'Delete failed because of constraint');
			}else{
				$em->remove($entity);
            	$em->flush();
			}
        }
        return $this->redirect($this->generateUrl('keio_baihoc'));
    }

    /**
     * Creates a form to delete a Baihoc entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}
